﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using Mani.Common;
using Ghasam.Business.Services;
using Ghasam.Business.Domain.Entity;
using System.Collections.Generic;

public partial class NewInternalAccounting : BasePage {

    private IInternalAccountingService internalAccountingService;
    private ISalesPersonService salesPersonService;

    public ISalesPersonService SalesPersonService
    {
        get { return salesPersonService; }
        set { salesPersonService = value; }
    }

    public IInternalAccountingService InternalAccountingService
    {
        get { return internalAccountingService; }
        set { internalAccountingService = value; }
    }

    public override string ActionName {
        get {
            return "vw_newinternalaccounting";
        }
    }

    protected void Page_Init(object sender, EventArgs e) {
        int count = 1;

        if ( String.IsNullOrEmpty(Request.QueryString["count"]) || !Int32.TryParse(Request.QueryString["count"], out count))
            generateControls(1);
        else
            generateControls(Convert.ToInt32(Request.QueryString["count"]));
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (CommonHelper.ShowHiddenCustomers()) {
            divType.Visible = true;
        }
        else {
            divType.Visible = false;
        }

        if (!Page.IsPostBack) {
            txtAccountingDate.Text = MyPersianDate.DateTimeToPersian(DateTime.Now);
            GetInternalAccountingTypes();
        }
    }

    private void GetInternalAccountingTypes()
    {
        ddlInternalAccountingType.DataSource = internalAccountingService.GetInternalAccountingTypes();
        ddlInternalAccountingType.DataBind();
    }

    protected void btnSave_Click( object sender, EventArgs e ) {
            InsertAccounting();
    }

    private void InsertAccounting() {

        string errorMessage = "";

        if (String.IsNullOrEmpty(txtInvoiceNumber.Text)) {
            UIHelper.ClientAlert(this, "لطفا شماره فاکتور را وارد کنید");
            return;
        }

        if ( String.IsNullOrEmpty(txtSalesPerson.Text) ) {
            UIHelper.ClientAlert(this, "لطفا فروشنده را انتخاب کنید");
            return;
        }

        SalesPerson salesPerson = SalesPersonService.FindByTitle(txtSalesPerson.Text);

        if (salesPerson == null) {
            UIHelper.ClientAlert(this, "فروشنده در لیست فروشندگان یافت نشد");
            return;
        }

        int count = (Request.QueryString["count"] == null) ? 1 : Convert.ToInt32(Request.QueryString["count"]);
        long invoiceNumber = Convert.ToInt64(txtInvoiceNumber.Text);
        float discount = 0;
        int type = Convert.ToInt32(ddlInternalAccountingType.SelectedValue);
        bool paid = cbPaid.Checked;

        if (!String.IsNullOrEmpty(txtDiscount.Text))
            discount = Convert.ToSingle(txtDiscount.Text);

        Dictionary<int, float> accountsDebit = new Dictionary<int, float>();
        
        for (int i = 0; i < count; i++) {

            TextBox txtQuantity = (TextBox)phInternalAccountingRows.FindControl("txtQuantity" + i);
            TextBox txtUnitPrice = (TextBox)phInternalAccountingRows.FindControl("txtUnitPrice" + i);

            if (String.IsNullOrEmpty(txtQuantity.Text) || String.IsNullOrEmpty(txtUnitPrice.Text))
                continue;
            
            Single quantity = Convert.ToSingle(txtQuantity.Text);
            Single unitPrice = Convert.ToSingle(txtUnitPrice.Text);
            Single debit = (quantity * unitPrice);
            DropDownList dropdownAccounts = (DropDownList)phInternalAccountingRows.FindControl("ddlAccounts" + i);
            String description = ((TextBox)phInternalAccountingRows.FindControl("txtDescription" + i)).Text;
            string itemName = ((TextBox)phInternalAccountingRows.FindControl("txtItems" + i)).Text;
            Item item = internalAccountingService.FindItemByName(itemName);
            if (item == null) {
                errorMessage += " - کالای " + itemName + " در لیست کالاها یافت نشد لطفا آیتم مربوطه را مجددا وارد کنید ";
                continue;
            }

            InternalAccounting iaccounting = new InternalAccounting();
            iaccounting.Account = internalAccountingService.GetAccount(Convert.ToInt32(dropdownAccounts.SelectedValue));
            iaccounting.Credit = 0;
            iaccounting.Debit = debit;
            iaccounting.Item = item;
            iaccounting.Quantity = quantity;
            iaccounting.UnitPrice = unitPrice;
            iaccounting.SalesPerson = salesPerson;
            iaccounting.AccountingType = internalAccountingService.GetInternalAccountingType(type);
            iaccounting.Paid = paid;
            iaccounting.Description = description;
            iaccounting.AccountingDate = MyPersianDate.PersianToDateTime(txtAccountingDate.Text);
            iaccounting.ModifyStamp = DateTime.Now;
            iaccounting.InvoiceNumber = invoiceNumber;

            internalAccountingService.NewInternalAccounting(iaccounting);

            if (accountsDebit.ContainsKey(iaccounting.Account.Id))
                accountsDebit[iaccounting.Account.Id] += iaccounting.Debit.Value;
            else
                accountsDebit.Add(iaccounting.Account.Id, iaccounting.Debit.Value);
        }

        int highestDebitAccountId = 0;
        float highestDebit = 0;

        Dictionary<int,float>.Enumerator en = accountsDebit.GetEnumerator();

        while (en.MoveNext())
        {
            if (highestDebitAccountId == 0)
            {
                highestDebitAccountId = en.Current.Key;
                highestDebit += en.Current.Value;
            }
            else if ( en.Current.Value > highestDebit )
            {
                highestDebitAccountId = en.Current.Key;
                highestDebit = en.Current.Value;
            }
        }

        if (discount != 0) {
            InternalAccounting credit = new InternalAccounting();
            credit.Account = internalAccountingService.GetAccount(highestDebitAccountId);
            credit.Credit = discount;
            credit.Debit = 0;
            credit.Item = null;
            credit.Quantity = 0;
            credit.UnitPrice = 0;
            credit.SalesPerson = salesPerson;
            credit.AccountingType = internalAccountingService.GetInternalAccountingType(type);
            credit.Paid = paid;
            credit.Description = "تخفیف فاکتور شماره " + invoiceNumber;
            credit.AccountingDate = MyPersianDate.PersianToDateTime(txtAccountingDate.Text);
            credit.ModifyStamp = DateTime.Now;
            credit.InvoiceNumber = invoiceNumber;
            internalAccountingService.NewInternalAccounting(credit);
        }

        if (String.IsNullOrEmpty(errorMessage)) {
            UIHelper.ClientAlert(this, "با موفقیت ثبت شد");
            UIHelper.ClientRedirect(this, "InternalAccounting.aspx");
        }
        else {
            UIHelper.ClientAlert(this, errorMessage);
            UIHelper.ClientRedirect(this, "NewInternalAccounting.aspx");
        }
    }

    private void generateControls(int count) {

        IList<InternalAccount> accounts = internalAccountingService.GetAccounts();
        IList<Item> items = internalAccountingService.GetItems();

        for (int i = 0; i < count; i++) {
            HtmlTableRow row = new HtmlTableRow();
            
            HtmlTableCell td1 = new HtmlTableCell();
            DropDownList drpAccounts = new DropDownList();
            drpAccounts.ID = "ddlAccounts" + i;
            drpAccounts.DataSource = accounts;
            drpAccounts.DataTextField = "Name";
            drpAccounts.DataValueField = "Id";
            drpAccounts.DataBind();
            td1.Controls.Add(drpAccounts);

            HtmlTableCell td2 = new HtmlTableCell();
            TextBox txtItems = new TextBox();
            txtItems.ID = "txtItems" + i;
            txtItems.AutoCompleteType = AutoCompleteType.Disabled;

            AjaxControlToolkit.AutoCompleteExtender ace = new AjaxControlToolkit.AutoCompleteExtender();
            ace.ID = "autoCompleteExtender" + i;
            ace.TargetControlID = "txtItems" + i;
            ace.ServicePath = "~/WebService/AutoCompleteService.asmx";
            ace.ServiceMethod = "GetItemName";
            ace.MinimumPrefixLength = 2;
            ace.CompletionInterval = 1000;
            ace.EnableCaching = true;
            ace.CompletionSetCount = 12;

            td2.Controls.Add(txtItems);
            td2.Controls.Add(ace);

            HtmlTableCell td3 = new HtmlTableCell();
            HtmlTableCell td4 = new HtmlTableCell();
            HtmlTableCell td5 = new HtmlTableCell();

            TextBox txtQuantity = new TextBox();
            TextBox txtUnitPrice = new TextBox();
            TextBox txtAmount = new TextBox();

            txtQuantity.ID = "txtQuantity" + i;
            txtQuantity.Width = 50;
            txtQuantity.Attributes.Add("autocomplete", "off");

            txtUnitPrice.ID = "txtUnitPrice" + i;
            txtUnitPrice.Width = 80;
            txtUnitPrice.Attributes.Add("autocomplete", "off");

            txtAmount.ID = "txtAmount" + i;
            txtAmount.Width = 80;
            txtAmount.Enabled = false;            
            
            td3.Controls.Add(txtQuantity);
            td4.Controls.Add(txtUnitPrice);
            td5.Controls.Add(txtAmount);

            HtmlTableCell td6 = new HtmlTableCell();
            TextBox txtDescription = new TextBox();
            txtDescription.ID = "txtDescription" + i;
            td6.Controls.Add(txtDescription);

            row.Controls.Add(td1);
            row.Controls.Add(td2);
            row.Controls.Add(td3);
            row.Controls.Add(td4);
            row.Controls.Add(td5);
            row.Controls.Add(td6);
            phInternalAccountingRows.Controls.Add(row);


            string javascript = "javascript:calculatePrice(@txtQuantity,@txtUnitPrice,@txtAmount)";
            javascript = javascript.Replace("@txtQuantity", txtQuantity.ClientID);
            javascript = javascript.Replace("@txtUnitPrice", txtUnitPrice.ClientID);
            javascript = javascript.Replace("@txtAmount", txtAmount.ClientID);

            txtQuantity.Attributes.Add("onchange", javascript);
            txtUnitPrice.Attributes.Add("onchange", javascript);
        }
    }

    protected void btnSaveItem_Click(object sender, EventArgs e) {
        Item item = new Item();
        item.Name = txtItemName.Text;
        item.Unit = txtItemUnit.Text;
        item.Deleted = false;
        item.ModifyStamp = DateTime.Now;
        item.CreateDate = DateTime.Now;
        internalAccountingService.PersistItem(item);

        txtItemName.Text = "";
        txtItemUnit.Text = "";
        lblMessage.Text = "کالا با موفقیت ذخیره شد";
    }

    private void AddAccount(int count, string value, string text) {
        for (int i = 0; i < count; i++) {
            Control control = phInternalAccountingRows.FindControl("ddlAccounts" + i);
            if (control != null) {
                DropDownList drpَAccount = (DropDownList)control;
                drpَAccount.Items.Add(new ListItem(text, value));
            }
        }
    }
    
    protected void btnGenerateRows_Click(object sender, EventArgs e) {
        Response.Redirect("NewInternalAccounting.aspx?count=" + txtCount.Text);
    }

    protected void btnSaveAccount_Click(object sender, EventArgs e) {
        InternalAccount account = new InternalAccount();
        account.Name = txtAccountName.Text;
        account.Description = txtAccountDescription.Text;
        internalAccountingService.NewInternalAccount( account );

        if (Request.QueryString["count"] == null)
            AddAccount(1, account.Id.ToString(), account.Name);
        else
            AddAccount(Convert.ToInt32(Request.QueryString["count"]), account.Id.ToString(), account.Name);

        txtAccountName.Text = "";
        txtAccountDescription.Text = "";
        lblAccountMessage.Text = "حساب با موفقیت ذخیره شد";
    }

    protected void btnSaveSalesPerson_Click(object sender, EventArgs e) {

        SalesPerson s = new SalesPerson();
        s.Title = txtSalesPersonTitle.Text;
        s.Phone = txtSalesPersonPhoneNumber.Text;
        s.Address = txtSalesPersonAddress.Text;
        s.Balance = 0;
        s.CreateDate = DateTime.Now;
        s.ModifyStamp = DateTime.Now;

        SalesPerson result = salesPersonService.SaveOrUpadate(s);
        
        txtSalesPersonAddress.Text = "";
        txtSalesPersonPhoneNumber.Text = "";
        txtSalesPersonTitle.Text = "";
        lblSalesPersonMessage.Text = "فروشنده با موفقیت ذخیره شد";
    }
}
